package com.kg.fiber.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.IOUtils;

import com.ivan.toolkit.common.Directory;
import com.ivan.toolkit.common.Dispatcher;
import com.kg.fiber.common.TimedDouble;

import lombok.extern.log4j.Log4j;

@Log4j
public abstract class Store extends Dispatcher<TimedDouble> {
	
	public static final Directory dir = new Directory("store");
		
	private long msStart = 0L;
	
	private CSVPrinter printer = null;
			
	@Override
	public void terminate() {
		super.terminate();
		IOUtils.closeQuietly(printer);
	}

	protected abstract String getTag();
	
	private CSVPrinter getPrinter(long millisecond) {
		
		long msLimit = 1800 * 1000;
		
		if(msStart != 0 && (millisecond - msLimit) >= msStart ) {
			
			IOUtils.closeQuietly(printer);			
			printer = null;
			
		}
		
		
		if(printer == null) {
			
			String filename = timeFmt.format(millisecond) + "_" + getTag() + ".csv";
			
			File f = dir.child(filename);
			
			try {
				
				printer = CSVFormat.DEFAULT.print(new FileWriter(f, true));
				
				msStart = millisecond;
				
			} catch (IOException e) {
				
				IOUtils.closeQuietly(printer);
				printer = null;
			}
			
		}
		
		return printer;
		
	}
	
	@Override
	protected void dispatch(TimedDouble event) {
		
		try {
			
			long ms = event.getTimestamp();
			
			CSVPrinter printer = this.getPrinter(ms);
			
			//String v = df.format(event.getValue());
			
			printer.printRecord(
					timeFmt2.format(ms),
					ms % 1000,
					event.getValue());
			
			printer.flush();
			
		} catch (IOException e) {
			log.error("Exception when store data: " + e.getMessage());
		}
		
	}
	
	//private final DecimalFormat df = 
	//		new DecimalFormat("#,##0.000000000000000");// 保留4位小数
	
	
	private final SimpleDateFormat timeFmt = 
			new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
	
	private final SimpleDateFormat timeFmt2 = 
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	
}
